<script lang="ts" setup>
import { debounce } from "@pureadmin/utils";
import * as echarts from "echarts";
import { defineProps, nextTick, onMounted, onUnmounted, ref, watchEffect } from "vue";
const props = defineProps<{
  data: {
    name?: string;
    unit?: string;
    max?: number;
    min?: number;
    data: number[];
    markLineData?: any[];
  };
  xAxisData?: string[];
  customoption?: any;
}>();
const chartRef = ref();
let myChart = null;
const charts = ref([]);
let getLeftData = (minVal, maxVal) => {
  const max = maxVal || 0;
  const min = minVal || 0;
  return {
    max,
    min
  };
};
const getCustomData = () => {
  const { data } = props;
  let yAxis: any = {};
  let series: any = {};
  const markLine = {
    silent: true,
    symbol: "none",
    data: []
  };

  const { name, unit, data: itemData, min, max, markLineData } = data;
  const NumArr = itemData.filter(item => item !== null);
  const minData = Math.min.apply(Math, NumArr);
  const maxData = Math.max.apply(Math, NumArr);
  const minValue = !(minData > min) ? minData : min;
  const maxValue = !(maxData < max) ? maxData : max;
  const diff = (maxData - minData) * 0.1;
  const ymin = minValue ? minValue || 0 : (minData - diff)?.toFixed(0);
  const ymax = maxValue ? maxValue || 0 : (maxData + diff)?.toFixed(0);
  let prevNum;

  const seriesData = itemData.map(num => {
    if (num || num === 0) {
      prevNum = num;
      return num;
    } else {
      return prevNum;
    }
  });
  // 1、yAxis
  yAxis = {
    name: unit,
    nameTextStyle: {
      color: "rgba(255,255,255,0.62)",
      fontSize: 11
    },
    show: true,
    splitNumber: 4,
    min: ymin,
    max: ymax,
    type: "value",
    splitLine: {
      show: true,
      lineStyle: {
        type: "dashed",
        color: "rgba(255, 255, 255, 0.25)"
      }
    },
    axisLabel: {
      color: "rgba(255,255,255,0.62)",
      fontSize: 11
    }
  };
  // 2、series
  series = {
    // name,
    type: "line",
    lineStyle: {
      width: 1,
      color: "rgba(0, 158, 255, 1)"
    },

    areaStyle: {
      origin: "start",
      color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
        {
          offset: 0,
          color: "rgba(0, 158, 255, 0.40)"
        },
        {
          offset: 1,
          color: "rgba(0, 158, 255, 0)"
        }
      ])
    },
    smooth: true,
    showSymbol: false,
    markLine: {},
    data: seriesData
  };
  // 3、markLine
  if (!markLineData) {
    const markLineItem = { max: data.max, min: data.min };

    Object.keys(markLineItem).map((key, ind) => {
      if (markLineItem[key] || markLineItem[key] === 0) {
        markLine.data.push({
          name,
          yAxis: markLineItem[key],
          symbol: "none",
          symbolSize: 0,
          lineStyle: {
            color: "rgba(245, 158, 11, 1)"
          },
          animation: false,
          label: {
            position: "insideEndTop",
            color: "rgba(245, 158, 11, 1)",
            formatter: () => {
              return markLineItem[key];
            }
          }
        });
      }
    });
  } else {
    markLine.data = markLineData;
    const arr = markLineData.map(item => item.yAxis);
    yAxis.min = Math.min.apply(Math, [...arr, minData]);
    yAxis.max = Math.max.apply(Math, [...arr, maxData]);
  }
  series.markLine = markLine;
  return { yAxis, series };
};
const handleRender = () => {
  const { xAxisData, customoption = {} } = props;
  const { yAxis, series } = getCustomData();
  const option = {
    animation: charts.value.length === 0,
    color: "rgba(255,255,255,0.62)",
    grid: {
      bottom: 0,
      left: 0,
      right: 14,
      top: 28,
      containLabel: true
    },
    tooltip: {
      trigger: "axis",
      appendToBody: true,
      formatter: function (params) {
        const [{ name, data }] = params;
        return `<div style="display:flex;align-items:center;">
            <div style="width: 8px;height: 3px;background: #009DFE;margin-right:3px;"></div>
            <div style="color: rgba(255,255,255,0.9);line-height: 18px;margin-right:12px">${name}</div>
            <div  style="color: rgba(255,255,255,0.9);line-height: 18px;font-weight: 600;">${data.toLocaleString()}</div>
          </div>`;
      },
      borderColor: "transparent",
      backgroundColor: "rgba(9,28,59,0.8)",
      padding: [3, 8],
      textStyle: {
        fontSize: 12
      },
      extraCssText:
        "box-shadow: 0px 5px 5px -3px rgba(0,0,0,0.1), 0px 8px 10px 1px rgba(0,0,0,0.06), 0px 3px 14px 2px rgba(0,0,0,0.05);border-radius: 3px;backdrop-filter: blur(1px);"
    },
    xAxis: [
      {
        type: "category",
        // boundaryGap: false,
        // axisLine: { onZero: false },
        axisLabel: {
          color: "rgba(255,255,255,0.62)",
          fontSize: 12
        },
        axisTick: {
          show: false
        },
        data: xAxisData
      }
    ],
    yAxis,
    series,
    ...customoption
  };

  try {
    option && myChart.setOption(option);
  } catch (error) {}
};
const initChart = () => {
  if (!chartRef.value) {
    return;
  }
  myChart = echarts.init(chartRef.value);
  handleRender();
  charts.value.push(myChart);
};
// 处理窗口大小变化
const handleResize = debounce(() => {
  charts.value.forEach(chart => {
    chart.resize();
  });
}, 60);
watchEffect(() => {
  handleRender();
});
onMounted(() => {
  nextTick(() => {
    initChart();
  });
  window.addEventListener("resize", handleResize);
});
onUnmounted(() => {
  window.removeEventListener("resize", handleResize);
  charts.value.forEach(chart => {
    chart.dispose();
  });
});
</script>
<template>
  <div ref="chartRef" class="chart-line"></div>
</template>
<style lang="scss" scoped>
.chart-line {
  width: 100%;
  height: 139rpx;
}
</style>
